function [dates, data] = gGapFill(dates, data, timestep)
%GGAPFILL Linearly interpolates and fills gaps regularly sampled timeseries
%   [DATES,DATA]=GGAPFILL(DATES,DATA) Attempts to determine the timestep 
%   by calculating the mode of the first difference of the supplied
%   date/times and fills any data gaps that exist in the supplied data with
%   a simple linear interpolation.
%
%   [DATES,DATA]=GGAPFILL(DATES,DATA,TIMESTEP) Uses the specified timestep
%   to construct a new timeseries in which to linearly interpolate onto to
%   fill gaps. TIMESTEP must be in the same numerical units as DATES. DATES
%   must be in floating point date format, the matlab format is preferred.
%
%   L. Winslow 2011-07-05
%   Last Revision: 2011-07-05.

if(nargin < 3)
    timestep = mode(diff(dates));
end

minDate = min(dates);
maxDate = max(dates);
n = floor((maxDate-minDate)/timestep)+1;
xx = linspace(minDate,maxDate,n)';

data = interp1(dates, data, xx, 'linear');
dates = xx;

end

